package com.zyl.pagergallery_java.viewModel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.zyl.pagergallery_java.R;
import com.zyl.pagergallery_java.pojo.Pixabay;
import com.zyl.pagergallery_java.volley.VolleyUtils;

import java.util.List;
import java.util.Random;

public class GalleryViewModel extends AndroidViewModel {
    public GalleryViewModel(@NonNull Application application) {
        super(application);
    }

    private MutableLiveData<List<Pixabay.PhotoItem>> mutableLiveData = new MutableLiveData<>();

    public LiveData<List<Pixabay.PhotoItem>> getLiveData() {
        return mutableLiveData;
    }

    //刷新数据
    public void fetchData() {
        final StringRequest stringRequest = new StringRequest(
                Request.Method.GET,
                getUrl(),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        List<Pixabay.PhotoItem> hits = gson.fromJson(response, Pixabay.class).getHits();
                        mutableLiveData.setValue(hits);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("myTAG", "onErrorResponse: JSON请求失败", error);
                    }
                }
        );

        VolleyUtils.getInstance(getApplication()).getRequestQueue().add(stringRequest);

    }

    private String getUrl() {
        Random random = new Random();
        return "https://pixabay.com/api/?key=20367884-4ff0b66c3d8b80b87f646de62&q=" + keyWork[random.nextInt(keyWork.length)];
    }

    String[] keyWork = {"Fish", "bear", "dragon", "sheep"};
}
